from collections import defaultdict


class Solution:
    def longestSubstring(self, s: str, k: int) -> int:
        cnts = [0] * 27
        for t in range(1, 27):
            # 该元素个数进行滑动窗口
            i = 0
            max_length = 0
            hash_words = defaultdict(int)
            for j in range(len(s)):
                hash_words[s[j]] += 1
                while len(hash_words) > t:
                    hash_words[s[i]] -= 1
                    if hash_words[s[i]] == 0:
                        del hash_words[s[i]]
                    i += 1
                if len(hash_words) == t and min(hash_words.values()) >= k:
                    max_length = max(max_length, j - i + 1)
            cnts[t] = max_length
        return max(cnts)


if __name__ == "__main__":
    s = Solution()
    r = s.longestSubstring(s="aaabb", k=3)
    print(r)
